package com.cssy.xxkj.logic.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.attach.entity.AttachFileUploadDO;
import com.cssy.xxkj.attach.service.IAttachFileUploadService;
import com.cssy.xxkj.attach.util.CommConstants;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicSalesDO;
import com.cssy.xxkj.logic.entity.LogicSalesItemDO;
import com.cssy.xxkj.logic.service.ILogicSalesService;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.OutJsonGrid;
/**
 * 销售订单控制器
 * @author hf
 *
 */
@Controller
@RequestMapping("/logic/sales")
public class SalesController extends BaseController<LogicSalesDO> {
	private static final String BILLTYPE ="type";//类型0/null销售订单1财务审核2生产审核
	
	private static final Logger logger = Logger.getLogger(SalesController.class);

	private static final String MANAGER = "/xxkj/logic/sales/SalesManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/sales/SalesOperation";// 添加、修改、显示页面
	private static final String BACK = "/xxkj/logic/sales/SalesBack";// 驳回已审核的且没有派工的销售订单
	
	@Resource(name = "logicSalesService")
	ILogicSalesService logicSalesService;
	//附件
	@Resource(name = "attachFileUploadService")
    private IAttachFileUploadService attachFileUploadService;
	//主数据公用集合Service
	@Resource(name="basicUtilService")
	private IBasicUtilService basicUtilService;
	
	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;

	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute(BILLTYPE, request.getParameter(BILLTYPE));
		return MANAGER;
	}
	
	/**
	 * 驳回
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/back")
	public String back(HttpServletRequest request, Model model)
			throws Exception{
		return BACK;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=oftenMothedUtil.getNoFinishConditions(scs, "zd024Billstatus", BillStatusUtil.SES_STATUS_FIVE);
		String type=request.getParameter(BILLTYPE);
		if("1".equals(type)){//财务审核
			List<String> str =new ArrayList<String>();
			str.add(BillStatusUtil.SES_STATUS_TWO);
			str.add(BillStatusUtil.SES_STATUS_THREE);
			str.add(BillStatusUtil.SES_STATUS_FOUR);
			str.add(BillStatusUtil.SES_STATUS_FIVE);
			scs.addCondition("zd024Billstatus", str);
		}
		if("2".equals(type)){//生产审核
			List<String> str =new ArrayList<String>();
			str.add(BillStatusUtil.SES_STATUS_THREE);
			str.add(BillStatusUtil.SES_STATUS_FOUR);
			str.add(BillStatusUtil.SES_STATUS_FIVE);
			scs.addCondition("zd024Billstatus", str);
		}
		scs.setOrderBy("bizCreatorDate desc");
		SearchResult result = logicSalesService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}
	
	/**
	 * 销售订单驳回
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/backList")
	public void backList(HttpServletRequest request, HttpServletResponse response)
			throws Exception{
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setRemovedProperty("g.removed");
		SearchResult result = logicSalesService.findBackListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		if (OperationFlag.ADD.equals(flag)) {// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicSalesDO sales = logicSalesService.findListById(id);
			model.addAttribute("sales", sales);
			
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("projectId", sales.getId());
			paramMap.put("fileRelated", CommConstants.FILE_RELATED_YES);
			List<AttachFileUploadDO> upFiles = attachFileUploadService.findAttachFileUploadDOs(paramMap);
			model.addAttribute("upFiles",upFiles);
			
		}
		model.addAttribute(BILLTYPE, request.getParameter(BILLTYPE));
		//客户列表
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("zd032Type", "客户", SearchCondition.OP_EQUAL);
		model.addAttribute("customer", basicUtilService.resultCompany(scs));
		return EIDT;
	}
	
	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicSalesDO so = logicSalesService.findListById(id);
			List<LogicSalesItemDO> soitem = logicSalesService.findSalesItemList(so.getId());
			OutJsonGrid out = new OutJsonGrid(soitem);
			out.printJSon(response);
		}
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSalesDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String itemdata = request.getParameter("itemdata");
			if (StringUtils.isBlank(itemdata)) {
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			if(StringUtils.isBlank(curAP.getZd002PiCode())){
				bodyMap.isFail();
				bodyMap.configWebInfor("PI编号不能为空！");
				return bodyMap.modelMap;
			}else{
				if(curAP.getZd026WithSingle()==1){
					if(!logicSalesService.checkPiCode(curAP.getZd002PiCode(),curAP.getId())){
						bodyMap.isFail();
						bodyMap.configWebInfor("PI编号已存在！请重新输入");
						return bodyMap.modelMap;
					}
				}
			}
			logicSalesService.salesSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields = ids.split(",");
			for (String field : fields) {
				LogicSalesDO ld = logicSalesService.findListById(field);
				logicSalesService.deleteBizRemoved(ld.getId());
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 驳回销售订单
	 */
	@RequestMapping("/backSale")
	@ResponseBody
	public Map<String, Object> backSale(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String backIds = request.getParameter("backIdStr");
			String zdSteps = request.getParameter("zdStepStr");
			if(StringUtils.isNotBlank(backIds)){
				String[] fieldStr = backIds.split(",");
				String[] stepStr = zdSteps.split(",");
				for(int i=0; i<fieldStr.length; i++){
					String backIdStr = fieldStr[i];
					String zdStepStr = stepStr[i];
					if(StringUtils.isBlank(backIdStr)){
						continue;
					}
					logicSalesService.backSale(backIdStr, zdStepStr, request);
				}
				bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			}
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	@RequestMapping("/getCustomer")
	public void getCustomer(HttpServletRequest request,
			HttpServletResponse response){
		String picode=request.getParameter("picode");
		SearchConditions scs= new SearchConditions();
		scs.setRemovedProperty("removed");
		scs.addCondition("zd002PiCode", picode, SearchCondition.OP_EQUAL);
		scs.addCondition("zd024Billstatus",
				Arrays.asList(BillStatusUtil.SES_STATUS_TWO,BillStatusUtil.SES_STATUS_THREE,
						BillStatusUtil.SES_STATUS_FOUR,BillStatusUtil.SES_STATUS_SEVEN,BillStatusUtil.SES_STATUS_FIVE));
		List<LogicSalesDO>  list=logicSalesService.findListByExample(scs).getResults();
		Map<String, Object> paramMap=new HashMap<String, Object>();
		if(list.size()>0){
			paramMap.put("msg", "success");
			paramMap.put("customerCode", list.get(0).getZd005CustomerCode());
			paramMap.put("customerName", list.get(0).getZd006CustomerName());
			paramMap.put("customerId", list.get(0).getZd004CustomerId());
		}else{
			paramMap.put("msg", list.size());
		}
		OutJsonGrid out = new OutJsonGrid(paramMap);
		out.printJSon(response);
	}	
}
